//
//  shenqing.m
//  shuilijuOASystem
//
//  Created by michael on 16/10/18.
//  Copyright © 2016年 czd. All rights reserved.
//

#import "shenqing.h"

@implementation shenqing

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
     self.method = @"toselectMeetPage";
    self.url = exchlogistics;
self.backgroundColor = [UIColor purpleColor];
[self initview];

          }
    return self;
}
- (void)initview{
_TableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, self.height) style:UITableViewStylePlain];
    self.TableView.delegate = self;
    self.TableView.dataSource =self;
    [self addSubview:_TableView];
            __weak typeof(self) weakSelf = self;

     [self.TableView addHeaderWithCallback:^{
        weakSelf.currentPage = 1;

        [weakSelf loadData]; //加载网络数据
    }];
    [self.TableView headerBeginRefreshing];
    
    [self.TableView addFooterWithCallback:^{
        if ((self.currentPage - 1)*KPageSize < self.totalCounts ){
             [weakSelf loadMore];
        }else{
        
            [weakSelf.TableView footerEndRefreshing];
            [weakSelf makeToast:@"没有更多了"];
    
        }
       
    }];
    NSDate *currentDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"YYYY-MM-dd"];
_sDate = [dateFormatter stringFromDate:currentDate];

}
- (void)loadData{

    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"sDate":_sDate},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools postWithURL:_url arrays:array method:_method success:^(id JSON) {
    NSLog(@"%@",JSON);
        if (self.currentPage ==1) {
           [self.dataArray removeAllObjects];
        }
        self.dataArray =  [self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]];
        [self.TableView reloadData];
        [self.TableView headerEndRefreshing];
        self.currentPage++;
        if (self.dataArray.count ==0) {
        [self makeToast:[NSString stringWithFormat:@"暂时还没有会议哦"]];
        }
    } failure:^(NSError *error) {
     [self.TableView headerEndRefreshing];
        
    }];
    
    

}

#pragma mark 加载更多
-(void)loadMore{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"sDate":_sDate},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools postWithURL:_url arrays:array method:_method success:^(id JSON) {
        [self.dataArray addObjectsFromArray:[self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]]];
        self.currentPage++;
                [self.TableView reloadData];

        [self.TableView footerEndRefreshing];
       
    } failure:^(NSError *error) {
         [self.TableView footerEndRefreshing];
    }];
    
}
//得到服务器返回数据中的标题
//传参数：一个服务器返回的二进制数据
-(NSMutableArray*)getDataList:(NSData*)data
{
    NSMutableArray * array = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（<交换 >）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（数据）
    NSArray *dataArray= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement * elemtenData in dataArray) {
    
        NSArray * subElement = [elemtenData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in subElement) {
            UnDoneModel * model = [[UnDoneModel alloc] init];
            GDataXMLElement * signElement = [[data elementsForName:@"是否编辑"] objectAtIndex:0];
            
            GDataXMLElement * titleElement = [[data elementsForName:@"标题"] objectAtIndex:0];
            GDataXMLElement * timeElement = [[data elementsForName:@"接收时间"] objectAtIndex:0];
            GDataXMLElement * nameElement = [[data elementsForName:@"上一办理人"] objectAtIndex:0];
            GDataXMLElement * stateElement = [[data elementsForName:@"公文状态"] objectAtIndex:0];
            GDataXMLElement * formElement = [[data elementsForName:@"表单"] objectAtIndex:0];
            GDataXMLElement * fileIdElement = [[data elementsForName:@"标识"] objectAtIndex:0];
            model.isSign = [signElement stringValue];
            model.title = [titleElement stringValue];
            model.time = [timeElement stringValue];
            model.name = [nameElement stringValue];
            model.state = [stateElement stringValue];
            model.form = [formElement stringValue];
            model.fileId = [fileIdElement stringValue];
            [array addObject:model];
        }
    }
    
    NSArray *countArray= [rootElement elementsForName:@"控制"];
    for (GDataXMLElement * data in countArray) {
        GDataXMLElement * countElement = [[data elementsForName:@"条数"] objectAtIndex:0];
        NSString * counts = [countElement stringValue];
        self.totalCounts = [counts intValue];
    }
    
//     self.title = [NSString stringWithFormat:@"会议(%lu)",(unsigned long)self.totalCounts];
   
    return array;
}
#pragma mark UITableView dataScource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.row==0) {
       UITableViewCell* cell = [[UITableViewCell alloc]init];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, cell.contentView.height)];

    label.text = @"点击选择时间";
    label.font = [UIFont systemFontOfSize:16];
    [cell.contentView addSubview:label];

    
    
_button1 = [UIButton buttonWithType:UIButtonTypeCustom];
NSLog(@"dateString:%@",_sDate);
      _button1.frame = CGRectMake(label.right+50, label.top, 110, label.height);
      [_button1 setTitle:_sDate forState:UIControlStateNormal];
    _button1.titleLabel.font = [UIFont systemFontOfSize: 15.0];
          [_button1 addTarget:self action:@selector(action1) forControlEvents:UIControlEventTouchUpInside];

     [_button1 setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];
            [cell.contentView addSubview:_button1];

   return cell;
}
 else{
 
  OAUnDoneListCell * cell = [OAUnDoneListCell cellWithTableView:tableView];
    UnDoneModel * model = self.dataArray[indexPath.row-1];
    cell.model = model;
    return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

if (indexPath.row == 0){
_selectDatePicker = [[MHDatePicker alloc] init];
    _selectDatePicker.isBeforeTime = YES;
    _selectDatePicker.datePickerMode = UIDatePickerModeDate;
    
    __weak typeof(self) weakSelf = self;
    [_selectDatePicker didFinishSelectedDate:^(NSDate *selectedDate) {
//        NSString *string = [NSString stringWithFormat:@"%@",[NSDate dateWithTimeInterval:3600*8 sinceDate:selectedDate]];
//        weakSelf.myLabel2.text = string;
      NSString *string = [weakSelf dateStringWithDate:selectedDate DateFormat:@"yyyy年MM月dd日"];
      _sDate = [string stringByReplacingOccurrencesOfString:@"年" withString:@"-"];
_sDate = [_sDate stringByReplacingOccurrencesOfString:@"月" withString:@"-"];
_sDate = [_sDate stringByReplacingOccurrencesOfString:@"日" withString:@""];

     //      _timebeforestring = string;
      [weakSelf.button1 setTitle:_sDate forState:UIControlStateNormal];
    }];


}else{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
      UnDoneModel * model = self.dataArray[indexPath.row-1];
    
    
            UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

    detailViewController * detailVC = (detailViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"detail"];
detailVC.fileId = model.fileId;
detailVC.type = @"huiyi";

[self.ViewController.navigationController pushViewController:detailVC animated:YES];
}
}

- (void)action1{
 _selectDatePicker = [[MHDatePicker alloc] init];
    _selectDatePicker.isBeforeTime = YES;
    _selectDatePicker.datePickerMode = UIDatePickerModeDate;
    
    __weak typeof(self) weakSelf = self;
    [_selectDatePicker didFinishSelectedDate:^(NSDate *selectedDate) {
//        NSString *string = [NSString stringWithFormat:@"%@",[NSDate dateWithTimeInterval:3600*8 sinceDate:selectedDate]];
//        weakSelf.myLabel2.text = string;
      NSString *string = [weakSelf dateStringWithDate:selectedDate DateFormat:@"yyyy年MM月dd日"];
      _sDate = [string stringByReplacingOccurrencesOfString:@"年" withString:@"-"];
_sDate = [_sDate stringByReplacingOccurrencesOfString:@"月" withString:@"-"];
_sDate = [_sDate stringByReplacingOccurrencesOfString:@"日" withString:@""];
_currentPage = 1;


 [self loadData];
//      [self.TableView reloadData];

      
      
//      _timebeforestring = string;
      [weakSelf.button1 setTitle:_sDate forState:UIControlStateNormal];
    }];

}
- (NSString *)dateStringWithDate:(NSDate *)date DateFormat:(NSString *)dateFormat
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:dateFormat];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    NSString *str = [dateFormatter stringFromDate:date];
    return str ? str : @"";
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{if(indexPath.row==0)
{
return 40;
}
else{

 UnDoneModel * model = self.dataArray[indexPath.row-1];
    CGFloat  titleFloat  = [OAToolBox sizebyText:model.title font:14 minsWidth:60];
    NSString * desstring = [NSString stringWithFormat:@"%@/%@/%@",model.time,model.state,model.name];
    CGFloat desFloat = [OAToolBox sizebyText:desstring font:14 minsWidth:80];
    return  titleFloat + desFloat + 20;
    }

//return  ( KScreenHeight-64)/10;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count+1;
}

@end
